package cn.tedu.carehome.foundation.unti;

import cn.tedu.carehome.foundation.pojo.vo.CheckInfoListItemVO;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExportExcel {
    private ExportExcel() {
    }

    /**
     *
     * @param filename 导出excel的文件名称
     * @param sheetname excel表sheet工作簿名称
     * @param dataList 导出的数据Vo
     * @param response 响应
     * @throws IOException 网络问题可能抛出异常
     * @Autor  Gaokang
     */
    public  static void  exportExcel(String filename, String sheetname,List<?> dataList, HttpServletResponse response) throws IOException
    {
        //excel文件名
        final String FILENAME = filename;
        //sheetName
        final String SHEETNAME = sheetname;
        //获取model对象类
        Class checkInfo = CheckInfoListItemVO.class;
        //表头样式策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置头居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        //初始化表格样式
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

//                response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(FILENAME, "UTF-8").replaceAll("\\+", "%20");
        //响应首部 Access-Control-Expose-Headers 就是控制“暴露”的开关，它列出了哪些首部可以作为响应的一部分暴露给外部。
        //此处设置了开放Content-Disposition，前端可获取该响应参数获取文件名称
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), checkInfo).autoCloseStream(Boolean.FALSE)
                .registerWriteHandler(horizontalCellStyleStrategy).sheet(SHEETNAME).doWrite(dataList);

    }
}
